package docqa

import (
	"oa-rest/common"
	"github.com/gin-gonic/gin"
)

// SelectAndAskHandler 选择文档并问答处理器
func SelectAndAskHandler(c *gin.Context) {
	var res common.Response
	var req SelectAndAskRequest

	// 绑定请求参数
	if err := c.ShouldBindJSON(&req); err != nil {
		res.Format(c, "参数解析失败: "+err.Error())
		return
	}

	// 参数验证
	if req.DocumentName == "" {
		res.Format(c, "文档名称不能为空")
		return
	}
	if req.Question == "" {
		res.Format(c, "问题不能为空")
		return
	}

	// 调用文档问答服务
	service := NewDocQAService()
	result, err := service.SelectAndAsk(req.DocumentName, req.Question)
	if err != nil {
		res.Format(c, "查询失败: "+err.Error())
		return
	}

	res.Data = result
	res.Format(c)
}

// AskHandler 基于session_id的问答处理器
func AskHandler(c *gin.Context) {
	var res common.Response
	var req AskRequest

	// 绑定请求参数
	if err := c.ShouldBindJSON(&req); err != nil {
		res.Format(c, "参数解析失败: "+err.Error())
		return
	}

	// 参数验证
	if req.SessionID == "" {
		res.Format(c, "会话ID不能为空")
		return
	}
	if req.Question == "" {
		res.Format(c, "问题不能为空")
		return
	}

	// 调用文档问答服务
	service := NewDocQAService()
	result, err := service.Ask(req.SessionID, req.Question)
	if err != nil {
		res.Format(c, "查询失败: "+err.Error())
		return
	}

	res.Data = result
	res.Format(c)
}

// SelectAndAskFormHandler 表单形式的选择文档并问答处理器
func SelectAndAskFormHandler(c *gin.Context) {
	var res common.Response

	// 从表单获取参数
	documentName := c.PostForm("document_name")
	question := c.PostForm("question")

	// 参数验证
	if documentName == "" {
		res.Format(c, "文档名称不能为空")
		return
	}
	if question == "" {
		res.Format(c, "问题不能为空")
		return
	}

	// 调用文档问答服务
	service := NewDocQAService()
	result, err := service.SelectAndAsk(documentName, question)
	if err != nil {
		res.Format(c, "查询失败: "+err.Error())
		return
	}

	res.Data = result
	res.Format(c)
}

// AskFormHandler 表单形式的问答处理器
func AskFormHandler(c *gin.Context) {
	var res common.Response

	// 从表单获取参数
	sessionID := c.PostForm("session_id")
	question := c.PostForm("question")

	// 参数验证
	if sessionID == "" {
		res.Format(c, "会话ID不能为空")
		return
	}
	if question == "" {
		res.Format(c, "问题不能为空")
		return
	}

	// 调用文档问答服务
	service := NewDocQAService()
	result, err := service.Ask(sessionID, question)
	if err != nil {
		res.Format(c, "查询失败: "+err.Error())
		return
	}

	res.Data = result
	res.Format(c)
}